//
//  RechargeViewController.m
//  HengYouCai
//
//  Created by ycgwl on 2017/5/2.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "RechargeViewController.h"
#import "PswInputView.h"
#import "ChangePasswordVC.h"
#import "BannerWebViewVC.h"
#import "RechangeWebVC.h"
#import "HengYouCai-Swift.h"
#import "GetBackPasswordVC.h"

@interface RechargeViewController ()<UITextFieldDelegate>
{
    // 是否同意协议
    BOOL _isAgree;
    // 获取数据是否失败
    BOOL _isFail;
    
}
//充值银行卡
@property (weak, nonatomic) IBOutlet UILabel *tableTitleLab;
@property (weak, nonatomic) IBOutlet UITextField *moneyTF;
@property (weak, nonatomic) IBOutlet UIButton *certainBtn;
//账户余额 标题
@property (weak, nonatomic) IBOutlet UILabel *titleLab;
//@property (weak, nonatomic) IBOutlet UIImageView *refreshImg;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet UILabel *agreeLab;
@property (weak, nonatomic) IBOutlet UIButton *protocolBtn;
// 账户余额
@property (weak, nonatomic) IBOutlet UILabel *yuE;

@property (weak, nonatomic) IBOutlet UILabel *detailLab;
@property (nonatomic, retain)NSDictionary *totalDic;
//充值金额
@property (weak, nonatomic) IBOutlet UILabel *amountLabel;
//支付方式
@property (weak, nonatomic) IBOutlet UILabel *payTypeLabel;

@property(nonatomic, strong) NSString * btnStatus;

@property (weak, nonatomic) IBOutlet UIImageView *paymentLogoImV;

@property (nonatomic, copy)NSString *bankSingleLimit;
/** 提交方式checkModelsms：验证码短信、pass：支付密码 */
@property(nonatomic, strong) NSString * checkModel;

//记录协议声明
@property(nonatomic,copy)NSString *protocolString;

@end

@implementation RechargeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //处理系统的调整偏移
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(kJcwGetNavHeight(), 0, 0, 0);
    
    
    
    _moneyTF.delegate = self;
    _isAgree = YES;
    _isRecharge = YES;
    self.agreeBtn.hidden = !_isRecharge;
    self.agreeLab.hidden = !_isRecharge;
    self.protocolBtn.hidden = !_isRecharge;
    
//    self.tableTitleLab.text = _isRecharge?@"充值银行卡":@"提现至银行卡";
    
//    self.title = _isRecharge?@"充值":@"提现";
//    self.moneyTF.placeholder = _isRecharge?@"最少充值100元":@"最高可提还不知道哦";
//    [self.certainBtn setTitle:_isRecharge?@"确认充值":@"确认提现" forState:UIControlStateNormal];
    WLGetWeakSelf(weakSelf, self);
    [[self.protocolBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        //
        BannerWebViewVC *normalWeb = [[BannerWebViewVC alloc] initWithUrlStr:HYC_PaymentProtocol title:self.protocolString];
        [weakSelf.navigationController pushViewController:normalWeb animated:YES];
        
    }];
    
    [self.moneyTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        //停用
        if ([weakSelf.btnStatus isEqualToString:@"1"]) {
            weakSelf.certainBtn.backgroundColor = Normal_UnselecBtnColor;
            weakSelf.certainBtn.enabled = NO;
            return;
        }
        
        double money = [x doubleValue];
        
        
        if (weakSelf.totalDic) {
            if (weakSelf.isRecharge) {
                if (money>=100) {
                    weakSelf.certainBtn.backgroundColor = Normal_RedColor;
                    weakSelf.certainBtn.enabled = YES;
                }else{
                    weakSelf.certainBtn.backgroundColor = Normal_UnselecBtnColor;
                    weakSelf.certainBtn.enabled = NO;
                }
            }
        }else{
            weakSelf.certainBtn.backgroundColor = Normal_UnselecBtnColor;
            weakSelf.certainBtn.enabled = NO;
        }
        
    }];
    
    
    //TODO:确认充值
    [[self.certainBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        
        /**
         充值
         */
        float rechargeMoney = weakSelf.moneyTF.text.floatValue;
        float limitMoney = weakSelf.bankSingleLimit.floatValue;
        if (limitMoney > 1) {
            if (rechargeMoney > limitMoney) {
                [weakSelf.view showHUDWarnTips:@"充值金额超出单笔限额" hideDelay:1.5];
                return;
            }
        }
        [weakSelf.view endEditing:YES];
        [weakSelf.view showHUDLoadingTips:@"充值中..."];
        if ([self.checkModel isEqualToString:@"pass"]) {//富有协议支付
            
            [weakSelf fyPay];
            
        }else if ([self.checkModel isEqualToString:@"sms"]){//宝付
            [HYCNetService paymentRechargeWithDict:@{@"amount":[NSString stringWithFormat:@"%.2f",weakSelf.moneyTF.text.floatValue]} onSuccess:^(NSDictionary *dictResult) {
                
                
                [weakSelf.view hideHUDLoading:0];
                
                NSString *length = dictResult[@"smsCodeMaxLen"];
                [[JCWBFInputSMSCodeAlertView alloc] initWithPhoneNumber:dictResult[@"phone"] num:length.integerValue sureHandler:^(NSString * smsCode) {
                    
                    [weakSelf bFPayWith:smsCode];
                }];
                
            } andFailed:^(NSInteger code, NSString *errorMsg) {
                //
                [weakSelf.view showHUDFailTips:errorMsg hideDelay:1];
            }];

        }else{
            [weakSelf.view showHUDFailTips:@"支付方式非法！" hideDelay:kHUDHideDelay];
        }
        

    }];
    
    
    [self statNetworking];
    
}

#pragma tableviewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
#pragma tableviewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RechargeCellID"];
    UIImageView *refreshImg = [cell viewWithTag:1004];
    refreshImg.hidden = !_isFail;
    
    if (_totalDic) {
        UIImageView *bankIcon = [cell viewWithTag:1001];
        UILabel *bankLab = [cell viewWithTag:1002];
        UILabel *kahaoLab = [cell viewWithTag:1003];
        bankLab.text = _totalDic[@"bankName"];
        kahaoLab.text = [NSString stringWithFormat:@"**** **** **** %@",_totalDic[@"bankCode"]];
        [bankIcon sd_setImageWithURL:[NSURL URLWithString:_totalDic[@"bankImageUrl"]]];
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_isFail) {
        [self statNetworking];
    }
    
}
#pragma scrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 滑动一定程度 退出键盘
    if (scrollView.contentOffset.y<-130) {
        //        [self.view endEditing:YES];
        
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSRange rangeItem = [textField.text rangeOfString:@"."];//判断字符串是否包含
    
    if (rangeItem.location != NSNotFound){
        if ([string isEqualToString:@"."]) {
            return NO;
        }else{
            //rangeItem.location == 0   说明“.”在第一个位置
            if (range.location>rangeItem.location+2) {
                return NO;
            }
        }
    }else{
        if ([string isEqualToString:@"."]) {
            if (textField.text.length<1) {
                textField.text = @"0.";
                return NO;
            }
            return YES;
        }
        if (range.location>10) {
            return NO;
        }
    }
    
    return YES;
}
/**
 数据源字典
 */
- (NSDictionary *)totalDic
{
    if (_totalDic) {
        _totalDic = [NSDictionary dictionary];
    }
    return _totalDic;
}

/**
 网络请求
 */
- (void)statNetworking
{
    [self.view showHUDLoading];
    WLGetWeakSelf(weakSelf, self);
    //
    //    [HYCNetService paymentFindPayMentListOnSuccess:^(NSDictionary *dictResult) {
    //        //
    //
    //        NSArray *list = dictResult[@"paymentList"];
    //        NSString *paymentCode = list.firstObject[@"paymentCode"];
    //        self.paymentCode = paymentCode;
    //
    //    } andFailed:^(NSInteger code, NSString *errorMsg) {
    //        //
    //    }];
    
    [HYCNetService paymentInitWithOnSuccess:^(NSDictionary *dictResult) {
        //没网的状态 填过了金额 点击刷新有网之后 btn不可点击问题
        if ([_moneyTF.text integerValue]>99&&_isAgree&&_isFail) {
            _certainBtn.backgroundColor = Normal_RedColor;
            _certainBtn.enabled = YES;
        }
        self.checkModel = dictResult[@"checkModel"];
        
        self.title = dictResult[@"title"];
        self.tableTitleLab.text = dictResult[@"bankLabel"];
        self.titleLab.text = dictResult[@"balanceLabel"];
        self.amountLabel.text = dictResult[@"amountLabel"];
        self.payTypeLabel.text = dictResult[@"paymentTypeLabel"];
       //确认按钮
        [self.certainBtn setTitle:dictResult[@"buttonLabel"] forState:UIControlStateNormal];
       //协议
        self.protocolString = dictResult[@"serviceAgreementLabel"];
        [self.protocolBtn setTitle:[NSString stringWithFormat:@"《%@》",dictResult[@"serviceAgreementLabel"]]
                          forState:UIControlStateNormal];
        
        _isFail = NO;
        _yuE.text = [NSString stringWithFormat:@"%@元",dictResult[@"availableMoney"]];
        _totalDic = dictResult;
        _moneyTF.placeholder = dictResult[@"amountTips"];
        
//        _moneyTF.placeholder = _isRecharge?@"最少充值100元":[NSString stringWithFormat:@"最高可提%@元",dictResult[@"availableMoney"]];
        self.detailLab.text = _isRecharge?dictResult[@"tips"]:dictResult[@"tips"];
        
        [self handleWarnWithStatus:dictResult[@"bankStatus"] warnStr:dictResult[@"bankTips"]];
        
        //新增支付逻辑 宝付支付
        NSDictionary * paymentDic = dictResult[@"payment"];
        //        self.paymentCode = paymentDic[@"paymentCode"];
        [self.paymentLogoImV sd_setImageWithURL:URLWithStr(paymentDic[@"paymentLogo"])];
        
        self.bankSingleLimit = dictResult[@"bankSingleLimit"];
        [weakSelf.view hideHUDLoading:0];
        [weakSelf.tableView reloadData];
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        //
        _isFail = YES;
        [weakSelf.tableView reloadData];
        [weakSelf.view showHUDFailTips:errorMsg hideDelay:1];
    }];
    
}

/**
 同意协议
 */
- (IBAction)agreeClick:(id)sender {
    
    UIButton *btn = sender;
    _isAgree = !_isAgree;
    [btn setImage:[UIImage imageNamed:_isAgree?@"recharge_invest_agre":@"recharge_invest_agre01"] forState:UIControlStateNormal];
    
    //停用
    if ([self.btnStatus isEqualToString:@"1"]) {
        _certainBtn.backgroundColor = Normal_UnselecBtnColor;
        _certainBtn.enabled = NO;
        return;
    }
    
    NSInteger money = [self.moneyTF.text integerValue];
    if (money>99&&_isAgree) {
        _certainBtn.backgroundColor = Normal_RedColor;
        _certainBtn.enabled = YES;
    }else{
 
        _certainBtn.backgroundColor = Normal_UnselecBtnColor;

        _certainBtn.enabled = NO;
    }
}


//bankTips  --String 类型    获取银行卡维护日志 ，若在维护中，则返回内容，否则返回 "" bankStatus
/**  处理银行维护公告(有值就公告)及提现按钮状态(0启用1停用) */
- (void)handleWarnWithStatus:(NSString *)statusStr warnStr:(NSString *)warnStr{
    self.btnStatus = statusStr;
    if (warnStr.length) {//公告有
        [self.tableView addSubview:[self getWarnNoticeView:warnStr]];
        [UIView animateWithDuration:0.618 animations:^{
            self.tableView.contentInset = UIEdgeInsetsMake(kJcwGetNavHeight()+23, 0, 0, 0);
        }];
    }else{
        [[self.tableView viewWithTag:100] removeFromSuperview];
        self.tableView.contentInset = UIEdgeInsetsMake(kJcwGetNavHeight(), 0, 0, 0);
    }
    //非1启用
    self.certainBtn.userInteractionEnabled = ![statusStr isEqualToString:@"1"];
    
}
//获取公告视图
- (UIView *)getWarnNoticeView:(NSString *)warnStr{
    UIView * temp = [[UIView alloc] initWithFrame:CGRectMake(0, -23, f_Device_w, 23)];
    temp.tag = 100;
    temp.backgroundColor = UIColorFromRGB(0xffe8bd);
    
    UIImageView * image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bank_inform"]];
    image.frame = CGRectMake(15, 5.25, 12.5, 12.5);
    [temp addSubview:image];
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake(32.5, 0, f_Device_w-32.5, 23)];
    lab.text = warnStr;
    lab.font = [UIFont systemFontOfSize:12];
    lab.textColor = Normal_RedColor;
    [temp addSubview:lab];
    return temp;
}


//MARK:宝付支付调起
- (void)bFPayWith:(NSString *)smsCode
{
    [self.view jcw_showGifLoading];
    WLGetWeakSelf(weakSelf, self);
    [HYCNetService paymentBaofooPaymentSubmitWithDict:@{@"smsCode": smsCode} OnSuccess:^(NSDictionary *dictResult) {
        [weakSelf.view hideHUDLoading:0];
        NSLog(@">>>%@<<<",dictResult);
        ZMBRechargeResultVC * vc = [[ZMBRechargeResultVC alloc] init];
        vc.payResultDic = dictResult;
        vc.isFromAccount = self.isFromAccount;
        [self pushVC:vc];
//        NSString * resultUrlStr = dictResult[@"resultUrl"];
//        if (resultUrlStr.length) {//有值 跳转充值结果展示网页
//            RechangeWebVC * vcWeb = [[RechangeWebVC alloc] init];
//            vcWeb.strTitle = dictResult[@"title"]?:@"支付结果";
//            vcWeb.isFromAccount = weakSelf.isFromAccount;
//            vcWeb.webUrl = resultUrlStr;
//            [weakSelf.navigationController pushViewController:vcWeb animated:YES];
//        }else{
//            [self.view showHUDFailTips:dictResult[@"message"] hideDelay:kHUDHideDelay];
//        }
        
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        [self.view showHUDFailTips:errorMsg hideDelay:kHUDHideDelay];
    }];
}

- (void)fyPay
{
    /**
     显示密码框
     */
    
    
    [self.view hideHUDLoading:0];
    [PswInputView initWithFrame:CGRectMake(0, 0, f_Device_w, f_Device_h) money:[NSString stringWithFormat:@"充值￥%@",[NSString stringWithFormat:@"%.2f",self.moneyTF.text.floatValue]] psdBlock:^(NSString *str, PswInputView *pswView) {
        
        /**
         获取到密码
         */
        [HYCNetService paymentSubmitWithDict:@{@"amount":self.moneyTF.text,@"payPassword":str} onSuccess:^(NSDictionary *dictResult) {
            //充值成功
            [self.view hideHUDLoading:0];
            [pswView removeFromSuperview];

            ZMBRechargeResultVC * vc = [[ZMBRechargeResultVC alloc] init];
            vc.payResultDic = dictResult;
            vc.isFromAccount = self.isFromAccount;
            [self pushVC:vc];
            
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            [self.view hideHUDLoading:0];
            
            if(code == 401){
                // 回到登录界面 移除密码框
                [pswView removeFromSuperview];
            }else {
                // 清空密码小黑点
                pswView.errorMessageLab.text = errorMsg;
                
                UIImageView *img1 = [pswView viewWithTag:10001];
                UIImageView *img2 = [pswView viewWithTag:10002];
                UIImageView *img3 = [pswView viewWithTag:10003];
                UIImageView *img4 = [pswView viewWithTag:10004];
                UIImageView *img5 = [pswView viewWithTag:10005];
                UIImageView *img6 = [pswView viewWithTag:10006];
                
                img1.hidden = YES;
                img2.hidden = YES;
                img3.hidden = YES;
                img4.hidden = YES;
                img5.hidden = YES;
                img6.hidden = YES;
                // 错误提示文字做动画
                CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
                animation.values = @[
                                     [NSValue valueWithCGPoint:pswView.errorMessageLab.layer.position],
                                     [NSValue valueWithCGPoint:CGPointMake(pswView.errorMessageLab.layer.position.x-20, pswView.errorMessageLab.layer.position.y)],
                                     [NSValue valueWithCGPoint:CGPointMake(pswView.errorMessageLab.layer.position.x+20, pswView.errorMessageLab.layer.position.y)],
                                     [NSValue valueWithCGPoint:pswView.errorMessageLab.layer.position]
                                     ];
                animation.keyTimes = @[
                                       @(0),@(0.3),@(0.7),@(1)
                                       ];
                animation.autoreverses = NO;
                animation.duration = 0.5;
                [pswView.errorMessageLab.layer addAnimation:animation forKey:@"anmi"];
                
            }
            
        }];
        
        
    } forgetPsd:^{
        
        /**
         忘记密码
         */
        GetBackPasswordVC *change = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"GetBackPasswordVCID"];
        [self.navigationController pushViewController:change animated:YES withHideBottomBarWhenPush:YES pop:YES];
    }];
}

@end

